<template>
    <div class="flex justify-center items-center w-full h-full text-white">
        <div v-if="!colors.length" class="flex flex-col items-center">
            <Uploader :after-read="getImage" />
            <div>请挑选一张照片吧 ヾ(≧▽≦*)o</div>
        </div>
        <div v-else class="flex flex-col items-center">
            <VanImage class="m-4" ref="image" height="100" :src="src" @click="ImagePreview([src])"></VanImage>
            <div>找到的颜色</div>
            <div class="flex">
                <div v-for="color in colors" class="h-6 w-6" :style="{ background: color }"></div>
            </div>
            <div class="text-white m-4">
                <div v-if="saving" class="flex items-center">
                    请输入色卡名称
                    <input
                        v-model="inputName"
                        type="text"
                        class="rounded-full bg-zinc-500 px-2 mx-2"
                    />

                    <button @click="saveToPallet" class="mx-4">确认</button>
                    <button @click="saving = false" class="mx-4">取消</button>
                </div>
                <div @click="saving = true" v-else>
                    <button>保存为色卡</button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
</style>

<script lang="ts" setup>
import { Uploader, Image as VanImage, ImagePreview } from 'vant';
import ColorThief from 'https://cdn.skypack.dev/colorthief'
import { ref } from 'vue';
import chroma from 'chroma-js';
import { useColorPanelStore } from './store';

const colorThief = new ColorThief()
const saving = ref(false)
const colors = ref([] as string[])
const src = ref('')
const inputName = ref('')
const getImage = async (file: any) => {
    const url = URL.createObjectURL(file.file)
    src.value = url
    const image = new Image()
    image.src = url
    image.onload = async () => {
        const palette = await colorThief.getPalette(image)
        console.log(palette);
        colors.value = palette.map(i => chroma.rgb(...i).hex())
    }
}
const store = useColorPanelStore()
const saveToPallet = () => {
    store.createPallet(inputName.value, colors.value)
    saving.value = false

}

</script>
